package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Intent;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.manager.AddressPickerManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PickChooseManager;
import com.ycsj.common.manager.PickerManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SnackbarUtil;
import com.ycsj.common.utils.UiUtils;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpCallBack;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.StateCodeUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.PopLvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.StudentInfo;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.builder.PostFormBuilder;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import me.iwf.photopicker.PhotoPicker;
import me.shaohui.advancedluban.Luban;
import me.shaohui.advancedluban.OnCompressListener;
import okhttp3.Call;

/**
 * 添加新学生和修改学生公用界面
 * Created by Administrator on 2018/6/27 0027.
 */

public class TeacherAddStudentActivity extends BaseActivity implements View.OnClickListener {

    //记录从班级小组界面传递过来的学生对象
    private StudentInfo info;

    private ImageView lvCommit;
    private RoundedImageView ivUserHeadimg;
    private TextView etUserChineseName;
    private TextView etUserEnglishName;
    private TextView tvUserSex;
    private TextView tvUserBirthday;
    private TextView etUserTel;
    private TextView tvUserAddress;
    private TextView etUserSchool;
    private TextView etUserGrade;
    private TextView etUserLove;
    private TextView tvUserState;
    private RelativeLayout llBaseMain;

    //跳转到编辑学生信息的请求码
    public static final int CHINESERNAME = 0X110;
    public static final int ENGLISEHNAME = 0X120;
    public static final int PHONE = 0X130;
    public static final int SCHOOL = 0X140;
    public static final int GRADE = 0X150;
    public static final int LOVE = 0X160;
    public static final int STATE = 0X170;
    //弹框的通用适配器
    private PopLvAdapter popLvAdapter;

    //选择头像图片的地址
    private String headPath = "";
    //记录编辑的中文名
    private String chineseName = "", oldChineseName = "";
    //记录编辑的英文名
    private String englishName = "", oldEnglishName = "";
    //记录选择的性别
    private String sex = "", oldSex = "";
    //记录选择的生日
    private String time = "", oldTime = "";
    //记录填写的电话
    private String tel = "", oldTel = "";
    //记录选择的地址
    private String address = "", oldAddress = "";
    //记录填写的学校
    private String school = "", oldSchool = "";
    //记录填写的年级
    private String grade = "", oldGrade = "";
    //记录填写的兴趣爱好
    private String love = "", oldLove = "";
    //记录自定义的缴费状态
    private String state = "", oldState = "";
    private RelativeLayout rlUserIcon;
    private RelativeLayout rlUserChineseNmae;
    private RelativeLayout rlUserEnglishNmae;
    private RelativeLayout rlUserSex;
    private RelativeLayout rlUserBirthday;
    private RelativeLayout rlUseTel;
    private RelativeLayout rlUserAddress;
    private RelativeLayout rlUserSchool;
    private RelativeLayout rlUserGrade;
    private RelativeLayout rlUserLove;
    private RelativeLayout rlUserState;
    private ImageView ivBack;
    private TextView tvTitle;
    private ImageView iv6;

    //上传的学生头像压缩的文件
    private File headfile;

    //Handler对象
    private Handler handler = new Handler();

    @Override
    protected int getContentLayout() {
        return R.layout.teacher_activity_add_student;
    }

    @Override
    protected void init() {

        initStateBar();

        //初始化视图
        initView();

        //初始化保存
        initSave();

        //获取Intent数据
        initIntent();
    }


    /**
     * 初始化视图
     */
    private void initView() {

        tvTitle = findViewById(R.id.tv_title);
        ivUserHeadimg = findViewById(R.id.iv_user_headimg);
        ivUserHeadimg.setOnClickListener(this);
        etUserChineseName = findViewById(R.id.et_user_chinese_name);
        etUserEnglishName = findViewById(R.id.et_user_english_name);
        tvUserSex = findViewById(R.id.tv_user_sex);
        tvUserBirthday = findViewById(R.id.tv_user_birthday);
        etUserTel = findViewById(R.id.et_user_tel);
        tvUserAddress = findViewById(R.id.tv_user_address);
        etUserSchool = findViewById(R.id.et_user_school);
        etUserGrade = findViewById(R.id.et_user_grade);
        etUserLove = findViewById(R.id.et_user_love);
        tvUserState = findViewById(R.id.tv_user_state);
        iv6 = findViewById(R.id.iv6);
        llBaseMain = findViewById(R.id.ll_main);
        lvCommit = findViewById(R.id.lv_edit);
        lvCommit.setOnClickListener(this);

        rlUserIcon = findViewById(R.id.rl_user_icon);
        rlUserIcon.setOnClickListener(this);

        rlUserChineseNmae = findViewById(R.id.rl_user_chinese_name);
        rlUserChineseNmae.setOnClickListener(this);

        rlUserEnglishNmae = findViewById(R.id.rl_user_english_name);
        rlUserEnglishNmae.setOnClickListener(this);

        rlUserSex = findViewById(R.id.rl_user_sex);
        rlUserSex.setOnClickListener(this);

        rlUserBirthday = findViewById(R.id.rl_user_birthday);
        rlUserBirthday.setOnClickListener(this);

        rlUseTel = findViewById(R.id.rl_user_tel);
        rlUseTel.setOnClickListener(this);

        rlUserAddress = findViewById(R.id.rl_user_address);
        rlUserAddress.setOnClickListener(this);

        rlUserSchool = findViewById(R.id.rl_user_school);
        rlUserSchool.setOnClickListener(this);

        rlUserGrade = findViewById(R.id.rl_user_grade);
        rlUserGrade.setOnClickListener(this);

        rlUserLove = findViewById(R.id.rl_user_love);
        rlUserLove.setOnClickListener(this);

        rlUserState = findViewById(R.id.rl_user_state);
        rlUserState.setOnClickListener(this);

        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);

    }


    /**
     * 初始化保存按钮
     */
    private void initSave() {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(UiUtils.dp2px(68), UiUtils.dp2px(30));
        lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        lp.addRule(RelativeLayout.CENTER_VERTICAL);
        lp.rightMargin = UiUtils.dp2px(12);
        lvCommit.setLayoutParams(lp);
        lvCommit.setVisibility(View.VISIBLE);

    }


    /**
     * 获取Intent对象
     */
    private void initIntent() {
        //证明是从班级信息界面点击小组上有学生的头像跳转过来的
        info = (StudentInfo) getIntent().getSerializableExtra("studentinfo");
        if (null != info) {

            lvCommit.setImageResource(R.drawable.img_save);
            //设置初始状态
            //修改标题
            tvTitle.setText(info.getName());

            //头像
            if (!info.icon.endsWith(".jpg")) {
                String headUrl = HttpAddress.HEADIMGURL + info.icon + ".jpg";
                ImageUtil.displayImage(this, ivUserHeadimg, headUrl, R.drawable.head_default);
            } else {
                String headUrl = HttpAddress.HEADIMGURL + info.icon;
                ImageUtil.displayImage(this, ivUserHeadimg, headUrl, R.drawable.head_default);
            }

            //中文名
            oldChineseName = info.getName();
            chineseName = info.getName();
            etUserChineseName.setText(oldChineseName);

            //英文名
            oldEnglishName = info.getNickname();
            englishName = info.getNickname();
            etUserEnglishName.setText(oldEnglishName);

            //性别
            sex = info.getGender();
            oldSex = info.getGender();
            tvUserSex.setText(oldSex);

            //生日
            String date = DateUtils.getYearAndMonthAndDay(info.getBirthday());
            time = date;
            oldTime = date;
            tvUserBirthday.setText(date);

            //电话
            tel = info.getTel();
            oldTel = info.getTel();
            etUserTel.setText(oldTel);
            iv6.setVisibility(iv6.INVISIBLE);

            //地址
            address = info.getAddress();
            oldAddress = info.getAddress();
            tvUserAddress.setText(oldAddress);

            //学校
            school = info.getSchool();
            oldSchool = info.getSchool();
            etUserSchool.setText(oldSchool);

            //年级
            grade = info.getGrade();
            oldGrade = info.getGrade();
            etUserGrade.setText(oldGrade);

            //兴趣爱好
            love = info.getFavorite();
            oldLove = info.getFavorite();
            etUserLove.setText(oldLove);

            //缴费状态
            state = info.getPayment();
            oldState = info.getPayment();
            tvUserState.setText(oldState);

        } else {
            tvTitle.setText("创 建 学 生");
            lvCommit.setImageResource(R.drawable.img_create);
        }
    }

    /**
     * 判断是否修改了学生信息的方法
     *
     * @return
     */
    private boolean hasUpdate() {
        boolean res = false;
        //头像,名称,地址,生日的比较
        if (!TextUtils.isEmpty(headPath)
                || (!TextUtils.isEmpty(oldChineseName) && !TextUtils.isEmpty(chineseName) && !oldChineseName.equals(chineseName))
                || (!TextUtils.isEmpty(address) && !TextUtils.isEmpty(oldAddress) && !address.equals(oldAddress))
                || (!TextUtils.isEmpty(time) && !TextUtils.isEmpty(oldTime) && !time.equals(oldTime))
        ) {
            res = true;
        }
        return res;
    }


    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.lv_edit) {
            //点击标题栏的创建,进行判空后进行服务器上传信息的操作
            if (info == null) {
                //创建新学生
                judgeAllByCreateNewStudent();
            } else {
                //修改学生信息
                judgeAllByUpdateStudent();
            }
        } else if (id == R.id.iv_user_headimg || id == R.id.rl_user_icon) {
            //点击用户头像跳转到相册选择界面或者进行系统拍照功能
            chooseHeadImgAction();
        } else if (id == R.id.rl_user_chinese_name) {
            //点击姓名(中文)的相对布局
            editStudentAction("名 称", CHINESERNAME);
        } else if (id == R.id.rl_user_english_name) {
            //点击姓名(英文)的相对布局
            editStudentAction("英 文 名", ENGLISEHNAME);
        } else if (id == R.id.rl_user_sex) {
            //点击性别的相对布局
            choosePop(0);
        } else if (id == R.id.rl_user_birthday) {
            //点击生日的相对布局
            chooseBirthdayPop();
        } else if (id == R.id.rl_user_tel) {
            //点击电话的相对布局
            if (info != null) {
                return;
            } else {
                editStudentAction("电 话", PHONE);
            }
        } else if (id == R.id.rl_user_address) {
            //点击地址的相对布局
            chooseAddressPop();
        } else if (id == R.id.rl_user_school) {
            //点击学校的相对布局
            editStudentAction("学 校", SCHOOL);
        } else if (id == R.id.rl_user_grade) {
            //点击年级的相对布局
            choosePop(2);
        } else if (id == R.id.rl_user_state) {
            //点击缴费状态的相对布局
            choosePop(1);
        } else if (id == R.id.iv_back) {
            finish();
        }
    }


    /**
     * 弹出选择地址的弹框
     */
    private void chooseAddressPop() {
        AddressPickerManager.showAddressPicker(this, new AddressPickerManager.onAddressSelectedListener() {
            @Override
            public void onChooseAddress(String res) {
                address = res;
                tvUserAddress.setText(address);
            }
        });
    }

    /**
     * 弹出选择生日的时间选择器,精确到年月日
     */
    private void chooseBirthdayPop() {

        PickerManager.showPickerByYeaerAndMonthAndDayBithday(this, new PickerManager.onSelectedListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                time = DateUtils.getTime(date, "yyyy-MM-dd");
                tvUserBirthday.setText(time);
            }
        });
    }

    /**
     * 通用弹框的PopUpWindow
     */
    private void choosePop(final int type) {
        final List<String> contents = new ArrayList<>();
        if (type == 0) {
            contents.add("男");
            contents.add("女");
        } else if (type == 1) {
            contents.add("已缴");
            contents.add("未缴");
            contents.add("自定义");
        } else if (type == 2) {
            for (int i = 1; i < 10; i++) {
                contents.add(i + "");
            }
        }
        //弹框
        PopUpManager.showPop(this, R.layout.teacher_pop_item_common, 0.3f, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {
                //标题
                TextView tvTitle = view.findViewById(R.id.tv_title);
                //列表
                ListView lv = view.findViewById(R.id.lv);
                //取消
                TextView tvCancel = view.findViewById(R.id.tv_cancel);

                if (type == 0) {
                    tvTitle.setText("性别");
                } else if (type == 1) {
                    tvTitle.setText("缴费状态");
                } else if (type == 2) {
                    tvTitle.setText("年级");
                }

                //设置列表数据
                popLvAdapter = new PopLvAdapter(TeacherAddStudentActivity.this, contents,
                        R.layout.teacher_lv_item_pop_common);
                lv.setAdapter(popLvAdapter);

                //条目点击事件
                lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                        if (type == 0) {
                            //性别
                            sex = contents.get(pos);
                            tvUserSex.setText(contents.get(pos));
                            PopUpManager.dismiss();
                        } else if (type == 1) {
                            //缴费状态
                            if (pos != contents.size() - 1) {
                                //不是最后一个自定义
                                state = contents.get(pos);
                                tvUserState.setText(contents.get(pos));
                            } else {
                                //跳转到自定义
                                editStudentAction("缴费状态", STATE);
                            }
                            PopUpManager.dismiss();
                        } else if (type == 2) {
                            grade = contents.get(pos);
                            etUserGrade.setText(contents.get(pos));
                            PopUpManager.dismiss();
                        }
                    }
                });

                //取消的点击事件
                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PopUpManager.dismiss();
                    }
                });
            }
        });
    }

    /**
     * 跳转到编辑学生信息的界面
     */
    private void editStudentAction(String title, int type) {
        Intent intent = new Intent(this, TeacherEditStudentActivity.class);
        intent.putExtra("title", title);
        intent.putExtra("type", type);
        startActivityForResult(intent, type);
    }

    /**
     * 选择头像的方法
     */
    private void chooseHeadImgAction() {
        PickChooseManager.startPhotoPickActivity(this, 1);
    }


    /**
     * 判断创建学生资料的完整性然后上传服务器的方法
     */
    private void judgeAllByCreateNewStudent() {
        //判断是否选择了头像
        if (TextUtils.isEmpty(headPath)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请选择头像", 0).show();
            return;
        }

        //判断是否输入了中文姓名
        if (TextUtils.isEmpty(chineseName)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请填写名称", 0).show();
            return;
        }

        //判断是否填写了电话
        if (TextUtils.isEmpty(tel)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请填写电话", 0).show();
            return;
        }

        //判断是否选择了地址
        if (TextUtils.isEmpty(address)) {
            address = "";
        }

        CustomDialogManager.show(this, "创建中...");

        //压缩文件
        if (!TextUtils.isEmpty(headPath)) {
            compressHeadFile();
        }

    }

    /**
     * 创建学生的操作
     */
    private void doPostCreateStu() {
        //先上传用户其它信息,在上传头像
        Map<String, String> map = new HashMap<>();
        map.put("type", "8");
        map.put("userID", AccountUtils.getAccount(this));
        map.put("name", chineseName);
        map.put("nickname", "");
        map.put("gender", sex);
        if (!TextUtils.isEmpty(time)) {
            //传了生日
            //取年月日
            String[] days = time.split("-");
            map.put("year", days[0]);
            map.put("month", days[1]);
            map.put("day", days[2]);
        } else {
            //没选择生日
            map.put("year", "2000");
            map.put("month", "01");
            map.put("day", "01");
        }
        map.put("tel", tel);
        map.put("address", address);
        map.put("school", school);
        map.put("grade", grade);
        map.put("teamnum", "-1");
        map.put("classnum", "-1");
        map.put("payment", state);
        if (headfile != null) {
//            map.put("icon", getIconName(headfile));
            map.put("icon", getCreateName());
        } else {
            map.put("icon", "");
        }

        HttpUtils.post(HttpAddress.CREATESTUDENT, map, this, new HttpCallBack<ResultInfo>() {
            @Override
            public void onSuccess(ResultInfo resultInfo) {
                if ("1".equals(resultInfo.state)) {
                    //创建学生上传除头像意外的其它信息后在上传头像
                    if (!TextUtils.isEmpty(headPath)) {
                        //表示修改了头像,压缩头像后上传
                        doPostHeadFile(headfile);
                    } else {
                        //没有修改头像信息,上传结束
                        CustomDialogManager.dissmiss();
                        ToastUtils.showShort("创建成功");
                    }
                } else if ("0".equals(resultInfo.state)) {
                    //上传失败
                    ToastUtils.showShort("该手机号已经绑定学生,请修改" + resultInfo.state);
                    CustomDialogManager.dissmiss();
                } else {
                    StateCodeUtils.showSateCode(resultInfo.state + "");
                    CustomDialogManager.dissmiss();
                }
            }

            @Override
            public void onError(String e) {
                ToastUtils.showShort("创建失败," + BaseApplication.ERROR);
                CustomDialogManager.dissmiss();
            }
        });
    }

    /**
     * 截取文件名
     */
    private String getIconName(File file) {
        String res = "";
        if (file != null) {
            String name = file.getName();
            if (!TextUtils.isEmpty(name)) {
                String[] names = name.split("\\.");
                //再次用_切割
                if (!TextUtils.isEmpty(names[0])) {
                    String[] split = names[0].split("_");
                    res = split[1];
                }
            }
        }
        return res;
    }

    /**
     * 获取创建学生时候的文件名
     */
    private String getCreateName() {
        String res = "";

        if (!TextUtils.isEmpty(tel)) {
            res = tel + "_0";
        }
        return res;
    }


    /**
     * 判断是否修改了学生信息然后上传服务器
     */
    private void judgeAllByUpdateStudent() {

        //修改过,重新上传学生信息
        //判断是否输入了中文姓名
        if (TextUtils.isEmpty(chineseName)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请填写中文名称", 0).show();
            return;
        }

        //判断是否选择了地址
        if (TextUtils.isEmpty(address)) {
            SnackbarUtil.ShortSnackbar(llBaseMain, "请选择地址", 0).show();
            return;
        }

        //判断是否修改学生的信息
        if (hasUpdate()) {

            CustomDialogManager.show(this, "修改中...");

            //如果修改了头像先上传其它信息,然后上传头像信息
            updataStuAciton();

        } else {
            SnackbarUtil.ShortSnackbar(llBaseMain, "未修改任何信息,不需要上传", Snackbar.LENGTH_SHORT).show();
        }
    }

    /**
     * 修改了学生上传学生信息
     */
    private void updataStuAciton() {
        Map<String, String> map = new HashMap<>();
        map.put("type", "9");
        map.put("userID", info.userID + "");
        map.put("name", chineseName);
        map.put("nickname", "");
        map.put("gender", sex);
        if (!TextUtils.isEmpty(time)) {
            //取年月日
            String[] days = time.split("-");
            map.put("year", days[0]);
            map.put("month", days[1]);
            map.put("day", days[2]);
        } else {
            map.put("year", "2000");
            map.put("month", "01");
            map.put("day", "01");
        }
        map.put("tel", info.tel);
        map.put("address", address);
        map.put("school", school);
        map.put("grade", grade);
        map.put("teamnum", info.teamnum + "");
        map.put("classnum", info.classnum + "");
        map.put("payment", state);
        map.put("favorite", love);
        map.put("id", info.getId() + "");

        if (!TextUtils.isEmpty(headPath)) {
            //修改了头像
            map.put("icon", getUpDateName());
        } else {
            //没修改头像
            map.put("icon", info.getIcon());
        }

        HttpUtils.post(HttpAddress.UPDATESTUDENT, map, this, new HttpCallBack<ResultInfo>() {
            @Override
            public void onSuccess(ResultInfo resultInfo) {
                if ("1".equals(resultInfo.state)) {
                    //上传除头像之类的其它信息成功
                    if (!TextUtils.isEmpty(headPath)) {
                        //表示修改了头像,压缩头像后上传
                        compressHeadFile();
                    } else {
                        //没有修改头像信息,上传结束
                        CustomDialogManager.dissmiss();
                        ToastUtils.showShort("修改成功");
                        sendUpdateMsg();

                    }
                } else {
                    //上传失败
                    ToastUtils.showShort("修改失败,错误码是:" + resultInfo.state);
                    CustomDialogManager.dissmiss();
                }
            }

            @Override
            public void onError(String e) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort("修改失败," + BaseApplication.ERROR);
            }
        });


    }

    /**
     * 通知班级信息界面刷新的方法
     */
    private void sendUpdateMsg() {

        //通知TeacherClassInfoAcitivity界面刷新
        BusInfo busInfo = new BusInfo();
        busInfo.type = TeacherClassInfoActivity.CREATEGROUPSUCCESS;
        EventBus.getDefault().post(busInfo);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 800);
    }

    /**
     * 压缩头像
     */
    private void compressHeadFile() {

        //先压缩头像
        File file = new File(headPath);

        //使用Luban压缩后上传文件
        Luban.compress(this, file).setMaxSize(150).setMaxHeight(1280).setMaxWidth(720)
                .putGear(Luban.CUSTOM_GEAR).launch(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        //开始压缩
                    }

                    @Override
                    public void onSuccess(File file) {
                        try {
                            if (info == null) {
                                //记录压缩后的上传文件
                                headfile = file;
                                //创建学生
                                doPostCreateStu();
                            } else {
                                //修改学生上传头像
                                headfile = file;
                                doPostHeadFile(headfile);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        //压缩错误
                        CustomDialogManager.dissmiss();
                    }
                });
    }

    /**
     * 上传头像信息
     *
     * @param file
     */
    private void doPostHeadFile(File file) {
        Map<String, String> map = new HashMap<>();
        map.put("type", "46");
        if (info != null) {
            //修改学生
            map.put("c", info.getUserID());
        } else {
            //创建学生
            map.put("c", AccountUtils.getAccount(this));
        }
        map.put("role", AccountUtils.getRole(this));
        map.put("platform", "2");


        PostFormBuilder post = OkHttpUtils.post();
        post.url(HttpAddress.UPDATAHEADIMG);
        post.params(map);
        if (info != null) {
            //修改学生头像
            post.addFile("name", getUpDateName() + ".jpg", file);
        } else {
            //创建学生头像
            post.addFile("name", getCreateName() + ".jpg", file);
        }
        post.tag(this);
        post.build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort(BaseApplication.ERROR);
            }

            @Override
            public void onResponse(String response, int id) {
                //上传成功
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        LogUtils.iTag("test", "数据解析异常");
                    }
                    if (info != null) {
                        if ("1".equals(info.state)) {
                            //修改除头像之类的其它信息成功
                            //没有修改头像信息,上传结束
                            CustomDialogManager.dissmiss();
                            ToastUtils.showShort("操作成功");
                            //通知TeacherClassInfoAcitivity界面刷新
                            sendUpdateMsg();
                        } else {
                            //修改失败
                            ToastUtils.showShort("操作失败,错误码是:" + info.state);
                            CustomDialogManager.dissmiss();
                        }
                    }
                }
            }
        });
    }

    /**
     * 获取修学生头像后上传的头像信息
     *
     * @return
     */
    private String getUpDateName() {
        String res = "";
        if (!TextUtils.isEmpty(info.getIcon())) {

            if (info.getIcon().contains("_")) {
                //包含下划线
                String[] split = info.getIcon().split("_");
                if (split != null && split.length != 0) {
                    String tel = split[0];
                    String afterNum = split[1];
                    int addNum = Integer.parseInt(afterNum) + 1;
                    if (addNum < 0) {
                        addNum = 0;
                    }

                    res = tel + "_" + (addNum);
                }
            } else {
                //不包含下划线
                res = info.getIcon() + "_0";
            }
        }
        return res;
    }

    /**
     * 选择头像后的回调处理
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //选择相册图片后的回调
        if (requestCode == PhotoPicker.REQUEST_CODE && resultCode == RESULT_OK) {
            if (data != null) {
                ArrayList<String> photos =
                        data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS);
                headPath = photos.get(0);
                //获取选择的头像地址
                ImageUtil.displayImage(this, ivUserHeadimg, headPath);
            }
        }


        //获取编辑后的学生的相关值
        if (data != null) {
            String result = data.getStringExtra("data");
            //选择编辑学生相关信息后的回调
            if (!TextUtils.isEmpty(result)) {
                if (requestCode == CHINESERNAME && resultCode == TeacherEditStudentActivity.CHINESERNAME) {
                    //中文名
                    chineseName = result;
                    etUserChineseName.setText(result);
                } else if (requestCode == ENGLISEHNAME && resultCode == TeacherEditStudentActivity.ENGLISEHNAME) {
                    //英语名
                    englishName = result;
                    etUserEnglishName.setText(result);
                } else if (requestCode == PHONE && resultCode == TeacherEditStudentActivity.PHONE) {
                    //电话
                    tel = result;
                    etUserTel.setText(result);
                } else if (requestCode == SCHOOL && resultCode == TeacherEditStudentActivity.SCHOOL) {
                    //学校
                    school = result;
                    etUserSchool.setText(result);
                } else if (requestCode == LOVE && resultCode == TeacherEditStudentActivity.LOVE) {
                    //兴趣爱好
                    love = result;
                    etUserLove.setText(result);
                } else if (requestCode == STATE && resultCode == TeacherEditStudentActivity.STATE) {
                    //缴费状态
                    state = result;
                    tvUserState.setText(result);
                }
            }
        }

    }


    @Override
    protected void onDestroy() {
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }
}
